﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Habi.Solver.ViewModels;
using DevExpress.Utils.MVVM.UI;
using DevExpress.XtraEditors;
using DevExpress.Utils.MVVM.Services;
using Habi.Solver.Services;
using Habi.Solver.Common;
using Habi.Solver.Models;
using DotNetExtensions.AspNet.DevExpress.Services;

namespace Habi.Solver.Views
{
    [ViewType(MainViewModel.ResourceMangeView)]
    public partial class ResourceMangeView : XtraUserControl
    {
        public ResourceMangeView()
        {
            InitializeComponent();
            searchControl.SetupSearchControl(windowsUIButtonPanel);
            mvvmContext.ViewModelType = typeof(ResourceViewModel);
            mvvmContext.RegisterService("FlyoutDocumentManagerService", WindowedDocumentManagerService.CreateFlyoutFormService(this));
            mvvmContext.RegisterService(new ControlOperationService(this));
            mvvmContext.RegisterService(new DialogMessageBoxService(this));
            if (!mvvmContext.IsDesignMode) InitializeView();
        }

        void InitializeView()
        {
            var fluent = mvvmContext.OfType<ResourceViewModel>();
            fluent.WithEvent(this, "Load").EventToCommand(x => x.Load());

            fluent.BindCommandAndImage(windowsUIButtonPanel.Buttons[0], x => x.Download());
            fluent.BindCommandAndImage(windowsUIButtonPanel.Buttons[1], x => x.Upload());
            fluent.BindCommandAndImage(windowsUIButtonPanel.Buttons[2], x => x.Publish());
            fluent.BindCommandAndImage(windowsUIButtonPanel.Buttons[4], x => x.ShowTask());

            fluent.SetBinding(gridControl, g => g.DataSource, x => x.Resources);

            gridView.SelectionChanged += (sender, e) =>
            {
                int[] indexs = gridView.GetSelectedRows();
                List<ResourceModel> resources = new List<ResourceModel>();
                foreach (var index in indexs)
                {
                    var resource = gridView.GetRow(index) as ResourceModel;
                    resources.Add(resource);
                }
                fluent.ViewModel.Selected = resources;
            };

            TaskContainer.Default.OnTaskCompleted += (e) =>
            {
                gridView.RefreshData();
            };

            TaskContainer.Default.OnTaskProgressChanging += (e) =>
            {
                gridView.RefreshData();
            };
        }
    }
}
